// pages/savepage/savepage.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        primary: app.globalData.primary, // 主题色
        ossPath: app.globalData.ossPath,
        d: null, // 模板编号
        pages: null,
        printBtn: false, //是否可印刷
        typeId: null,// 产品id
        writePhotosAlbum: false , // 保存图片授权
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        //设置主题色
        if (app.globalData.primary) {
            this.setData({ primary: app.globalData.primary })
            app.usePrimary(app.globalData.primary)
        }
        // options.d = 146234
        this.setData({
            d: options.d
        })
    },
    getTemplate() { // 查询模板信息
        wx.showLoading({
            title: '设计生成中',
        })
        wx.request({
            url: app.globalData.serverPath + '/Document',
            method: 'post',
            header: app.globalData.header,
            data: 'DocumentNumber=' + this.data.d + '&TeamNum=' + app.globalData.user.team,
            success: (res) => {
                wx.hideLoading()
                let data = res.data;
                this.setData({
                    pages: data.Pages,
                    printBtn: data.ProductType.OnlinePrint_Status,
                    typeId: data.TypeId
                })
            }
        })
    },
    handleLoad: function() { // 图片加载完成
        
    },
    saveImgToLocal() { // 保存图片到本地
        if (!this.data.pages.length) return;
        this.getScope().then((type) => {
            console.log('type', type)
            if (!type) {
                wx.showToast({
                    title: '没有权限,无法保存!',
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            Promise.all(Array.from(this.data.pages).map(item => {
                var imgSrc = app.globalData.ossPath + item.Thumb
                console.log(imgSrc)
                // var imgSrc = 'https://img.aliyin.com/docs/pngs/201908/25083a7d96004984a9cdec261b9935bc.png?'
                wx.showLoading({
                    title: '保存图片中',
                })
                return new Promise(resolve => {
                    this.downImg(imgSrc).then((res) => {
                        resolve()
                    })
                }) 
            })).then(() => {
                wx.hideLoading();
                wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                })
            })
            
        })

    },
    getScope: function () { //获取相册授权
        return new Promise(resolve => {
            
            wx.getSetting({
                success: (res) => {
                    if (!res.authSetting['scope.writePhotosAlbum']) {
                        wx.authorize({
                            scope: 'scope.writePhotosAlbum',
                            success() {
                                resolve(true)
                            },
                            fail: (err) => {
                                console.log(err)
                                if (this.data.writePhotosAlbum) {
                                    wx.showModal({
                                        title: '提示',
                                        content: '是否重新授权',
                                        success(res) {
                                            if (res.confirm) {
                                                wx.openSetting({
                                                    success: res => {
                                                        console.log(res)
                                                        if (res.authSetting['scope.writePhotosAlbum']) {
                                                            resolve(true)
                                                        } else {
                                                            resolve(false)
                                                        }
                                                    }
                                                })
                                            } else if (res.cancel) {
                                                resolve(false)
                                            }
                                        }
                                    })
                                } else {
                                    this.setData({
                                        writePhotosAlbum: true
                                    })
                                }
                                
                            }
                        })
                    } else {
                        resolve(true)
                    }
                }
            })
        })
    },
    downImg: function (imgSrc) { // 下载图片
        return new Promise(resolve => {
            wx.downloadFile({
                url: imgSrc,
                success: function (res) {
                    // console.log(res);
                    //图片保存到本地
                    wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: (res) => {
                            
                            resolve(res)
                        },
                        fail: () => resolve()
                    })
                }
            })
        })
       
    },
    gotoPrint: function() { // 去下单印刷
        wx.showLoading({
            title: '生成印刷模板',
        })
        wx.request({
            url: app.globalData.serverPath + '/ShopDocument',
            method: 'post',
            header: app.globalData.header,
            data: 'documentnum=' + this.data.d,
            success: ({data}) => {
                if (data.state == 'ok') {
                    wx.navigateTo({
                        url: '../production/production?id=' + this.data.typeId + '&d=' + data.msg + '&thumb=' + this.data.pages[0].Thumb,
                    })
                }
            },
            fail: () => {
                wx.showToast({
                    title: '请稍后再试',
                    icon: 'warning',
                    duration: 2000
                })
            },
            complete: () => {
                wx.hideLoading()
            }
        })
        
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.getTemplate();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})